package com.auto.survey.activity.monitoring.ctrlmeasure

import android.content.Intent
import android.graphics.Color
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_OBJECT_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_PROJET_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_STATION_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_TASK_ID
import com.auto.survey.activity.monitoring.adapter.CtrlAddManagerAdapter
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.activity.monitoring.entity.MonitoringPoint
import com.auto.survey.activity.monitoring.entity.MonitoringPointCtrlObservation
import com.auto.survey.activity.monitoring.entity.ctrlmeasure.ClosedLoopWithPoints
import com.auto.survey.activity.monitoring.entity.ctrlmeasure.LoopObservationPoint
import com.auto.survey.base.BaseActivity
import com.auto.survey.util.Helper
import com.auto.survey.widget.CentreToast
import com.auto.survey.widget.CommonTitle.Companion.TEXT_POSITON_RIGHT
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 新建控制测点管理类
 */
class CtrlMeasureManagerActivity: BaseActivity() {
    private var projectId:Int = -1
    private var objectId:Int = -1
    private var stationId:Int = -1

    private var taskId:Int = -1

    private val database = MonitoringRepository()

    private var closedLoopWithPoints: ClosedLoopWithPoints?=null

    override fun initView() {
        projectId = intent.getIntExtra(KEY_INTENT_PROJET_ID, -1)
        objectId = intent.getIntExtra(KEY_INTENT_OBJECT_ID, -1)
        stationId = intent.getIntExtra(KEY_INTENT_STATION_ID, -1)
        taskId = intent.getIntExtra(KEY_INTENT_TASK_ID, -1)
        val choicedList = mutableListOf<MonitoringPoint>()
        var selectedList =  mutableListOf<MonitoringPoint>()

        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("测点选择")

        mComment_title?.setRightTitle("保存")
        mComment_title?.setTitleColor(Color.WHITE, TEXT_POSITON_RIGHT)
        mComment_title?.setOnRightTextClickListener(Helper.debounce{
            lifecycleScope.launch {
                //1步 简化赋值逻辑，明确变量含义
                closedLoopWithPoints = database.getTaskPointList(taskId)
                closedLoopWithPoints?.monitoringPoints = choicedList

                // 步骤2：创建观测点列表（基础部分）
                val loopObsPoints = runCatching {
                    choicedList.mapIndexed { index, point ->
                        LoopObservationPoint(
                            loopId = taskId,
                            pointId = point.id,
                            orderInLoop = index
                        )
                    }.toMutableList()
                }.getOrNull() ?: run {
                    showError("步骤2失败：创建观测点列表失败")
                    return@launch
                }

                // 3步 单独添加最后一个闭环元素（复用第一个元素的id，索引为choicedList.size）
                if (choicedList.isNotEmpty()) { // 增加空安全判断，避免索引越界
                    loopObsPoints.add(LoopObservationPoint(
                        loopId = taskId,
                        pointId = choicedList.first().id,
                        orderInLoop = choicedList.size
                    ))
                }

                //4步 保存观测点关联
                database.addTaskPoints(loopObsPoints)

                //5步 处理闭环起点/终点设置，增加空列表安全校验
                closedLoopWithPoints?.loop?.let { loop ->
                    if (loopObsPoints.isNotEmpty()) {
                        val firstPointId = loopObsPoints.first().pointId
                        val pointExists = database.getMonitoringPointById(firstPointId) != null
                        loop.startPointId = firstPointId
                        loop.endPointId = firstPointId  // 若业务需要终点为最后一个，可改为loopObsPoints.last().id
                        // 直接更新任务（已通过let确保loop非空）
                        if (pointExists) {
                            database.updateTask(loop)
                        }
                    }

                }
                //6步
                val ctrlmeasureObservations = choicedList.mapIndexed { index, point ->
                    MonitoringPointCtrlObservation(monitoringPointId = point.id, observationTime=null,
                        horizontalAngleL=null, verticalAngleL=null, distanceL=null,
                        horizontalAngleR = null, verticalAngleR=null, distanceR = null,
                        measure2C=null, measure2D=null)
                }.toMutableList()

                //7步
                if (choicedList.isNotEmpty()) { // 增加空安全判断，避免索引越界
                    ctrlmeasureObservations.add(
                        MonitoringPointCtrlObservation(
                            monitoringPointId = choicedList.first().id, observationTime=null,
                        horizontalAngleL=null, verticalAngleL=null, distanceL=null,
                        horizontalAngleR = null, verticalAngleR=null, distanceR = null,
                        measure2C=null, measure2D=null))
                }
               database.addMonitoringPointCtrlObservation(ctrlmeasureObservations)

                //8步
                withContext(Dispatchers.Main) {
                    val intent = Intent()
                    intent.putExtra(KEY_INTENT_PROJET_ID, projectId)
                    intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
                    intent.putExtra(KEY_INTENT_STATION_ID, stationId)
                    intent.putExtra(KEY_INTENT_TASK_ID, taskId)
                    intent.setClass(this@CtrlMeasureManagerActivity, CtrlMeasureListActivity::class.java)
                    startActivity(intent)
                    finish()
                }

            }
        })



        val rv_choiced = findViewById<RecyclerView>(R.id.rv_add_ctrl_choiced)
        rv_choiced.layoutManager = GridLayoutManager(this@CtrlMeasureManagerActivity, 4)
        val choicedAdapter = CtrlAddManagerAdapter()
        rv_choiced.adapter = choicedAdapter
        val callbak = GridDragCallback(choicedAdapter)
        val itemTouchHelp = ItemTouchHelper(callbak)
        itemTouchHelp.attachToRecyclerView(rv_choiced)
        choicedAdapter.setItemTouchHeler(itemTouchHelp)



        val rv_dochoic = findViewById<RecyclerView>(R.id.rv_add_ctrl_dochoice)
        rv_dochoic.layoutManager = GridLayoutManager(this@CtrlMeasureManagerActivity, 4)
        val dochoiceAdapter = CtrlAddManagerAdapter()
        rv_dochoic.adapter = dochoiceAdapter


        choicedAdapter.setDeleItemClickListener(object : CtrlAddManagerAdapter.onItemDeleteClickListener{
            override fun onDelteItemClick(point: MonitoringPoint, position: Int) {
                callbak.stopDragging()
                // 关键修复1：从已选列表数据中移除该项
                choicedList.remove(point)
                // 关键修复2：通知已选列表适配器删除对应位置项
                choicedAdapter.notifyItemRemoved(position)
                // 修复3：如果后续项位置变化，需通知更新
                choicedAdapter.notifyItemRangeChanged(position, choicedList.size - position)

                // 同步更新待选列表（原逻辑保留）
                // 关键修复：同步更新两个列表的状态
                val indexInSelected = selectedList.indexOfFirst { it.id == point.id }
                if (indexInSelected != -1) {
                    selectedList[indexInSelected] = selectedList[indexInSelected].copy(isWarning = false)
                    dochoiceAdapter.notifyItemChanged(indexInSelected)
                }
            }

        })

        dochoiceAdapter.setItemClickListener(object : CtrlAddManagerAdapter.OnItemClickListener{
            override fun onItemClick(point: MonitoringPoint, position: Int) {
                if (!choicedList.contains(point)) {
                    choicedList.add(point)
                    choicedAdapter.setData(choicedList)
                }
            }

        })


        lifecycleScope.launch {
            database.getMonitoringPointClloectedByStationId(stationId).collect{
                selectedList.clear()
                selectedList.addAll(it)
                dochoiceAdapter.setData(selectedList)
            }
        }

    }

    // 错误提示辅助函数
    private fun showError(message: String) {
        runOnUiThread {
            CentreToast.instance.showText(message)
        }
    }

    override fun getLayoutId(): Int {

        return R.layout.activity_ctrl_measure_add
    }
}